package db

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"new_ginblog/config"
	"new_ginblog/internal/middleware"
	"new_ginblog/internal/models"
)

var (
	DB    *gorm.DB
	Error error
)

func InitDb() {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",
		config.DbUser,     // 用户名
		config.DbPassword, // 密码
		config.DbHost,     // 主机
		config.DbPort,     // 端口
		config.DbName,     // 架构名
	)
	DB, Error = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if Error != nil {
		middleware.SugarLogger.Panic(Error)
	}

	// 根据后端项目编写的表结构自动在数据库里面创建表 实现表格的自动迁移
	if err := DB.AutoMigrate(&models.Article{}, &models.Category{}, &models.User{}); err != nil {
		middleware.SugarLogger.Panic(err)
	}
}
